<template>
  <div class="question-list">
    <!-- 筛选组件 -->
    <div class="question-filter">
      <el-form
        :inline="true"
        label-position="right"
        label-width="80px"
        :class="{ 'simple-filter': true }"
        size="small"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.subject_id"
                placeholder="请选择学科"
                clearable
                @clear="get_list"
              >
                <el-option
                  v-for="item in treeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.directory_id"
                placeholder="请选择目录"
                clearable
              >
                <el-option
                  v-for="item in directoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.tag_id"
                placeholder="请选择标签"
                clearable
              >
                <el-option
                  v-for="item in tagList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.quest_type"
                placeholder="选择题型"
                :disabled="false"
                clearable
              >
                <el-option label="单选题" :value="1"></el-option>
                <el-option label="多选题" :value="2"></el-option>
                <el-option label="判断题" :value="3"></el-option>
                <el-option label="简答题" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.check_state"
                :disabled="true"
                placeholder="请选择审核状态"
                clearable
              >
                <el-option label="待审核" :value="1"></el-option>
                <el-option label="审核通过" :value="2"></el-option>
                <el-option label="不通过" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.show_state"
                :disabled="true"
                placeholder="请选择发布状态"
                clearable
              >
                <el-option label="上架" :value="1"></el-option>
                <el-option label="下架" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-input
                v-model="query.create_name"
                placeholder="请输入创建者"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.difficulty"
                placeholder="请选择难度"
                clearable
              >
                <el-option label="简单" :value="1"></el-option>
                <el-option label="中等" :value="2"></el-option>
                <el-option label="较难" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-select
                v-model="query.is_true_question"
                placeholder="请选择是否真题"
                clearable
              >
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="">
              <el-date-picker
                v-model="time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 简洁模式 -->
          <el-col v-if="true" :span="5" :offset="3">
            <el-form-item>
              <el-button type="primary" size="small" @click="searchsubmit"
                >查询</el-button
              >
              <el-button @click="searchcancel">重置</el-button>
              <el-button
                @click="simpleModel = !simpleModel"
                plain
                :icon="
                  simpleModel ? 'el-icon-folder-remove' : 'el-icon-folder-add'
                "
                type="warning"
              ></el-button>
            </el-form-item>
          </el-col>
          <!-- 非简洁模式 -->
          <el-col :span="4" v-else :offset="4">
            <el-form-item>
              <el-button type="primary" size="small" @click="searchsubmit"
                >查询</el-button
              >
              <el-button @click="searchcancel" size="small">重置</el-button>
              <el-button
                @click="simpleModel = !simpleModel"
                plain
                size="small"
                :icon="
                  simpleModel ? 'el-icon-folder-remove' : 'el-icon-folder-add'
                "
                type="warning"
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 列表组件 -->
    <div class="table-bg">
      <!--   列表信息  -->
      <el-table
        :data="list"
        v-loading=""
        border
        row-key="id"
        ref="tableList"
        @selection-change="multipleSelection = $event"
      >
        <el-table-column
          label="#"
          width="60"
          align="center"
          type="selection"
        ></el-table-column>
        <el-table-column label="试题信息">
          <template slot-scope="scope">
            <!-- 试题项目 -->
            <question-item
              :simple-model="simpleModel"
              :question="scope.row"
            ></question-item>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <Pagination
      :total="total"
      :page.sync="query.page"
      :limit.sync="query.limit"
      @pagination="pagination_change"
    />
    <!-- 审核弹框 -->
    <el-dialog
      title="试题审核"
      :visible.sync="checkShow"
      width="30%"
      @close="checkCancel"
    >
      <el-form
        :model="checkFormData"
        ref="checkFormData"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="审核结果">
          <el-radio-group v-model="checkFormData.check_state">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            rows="3"
            type="textarea"
            v-model="checkFormData.check_remarks"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkSubmit">确定</el-button>
          <el-button @click="checkCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getQuestionList,
  getTreeList,
  editQuestionShow,
  deleteQuestion,
  editQuestionCheck,
} from "@/api/exam/question";
import QuestionItem from "@/components/QuestionItem";
import Pagination from "@/components/Pagination";
const defaultItem = {
  subject_id: "",
  directory_id: "",
  tag_id: "",
  difficulty: "",
  quest_type: "",
  is_true_question: "",
  show_state: 1,
  check_state: 2,
  create_name: "",
};
export default {
  name: "QuestionListPaper",
  props: {
    quest_type: {
      required: true,
    },
    selectList: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      query: {
        ...defaultItem,
        page: 1,
        limit: 10,
        subject_id: "",
        directory_id: "",
      },
      treeList: [],
      simpleModel: true,
      multipleSelection: [], // 选中项
      time: [],
      total: 0,
      checkShow: false, // 审核表单弹框
      checkFormData: {
        // 审核表单
        id: "",
        check_state: 2,
        check_remarks: "",
      },
    };
  },
  components: {
    QuestionItem,
    Pagination,
  },
  computed: {
    directoryList() {
      // 目录信息
      if (!this.query.subject_id) {
        return [];
      } else {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.query.directory_id = "";
        const result = this.treeList.find(
          (val) => val.id == this.query.subject_id
        );
        return result.children;
      }
    },
    tagList() {
      // 标签信息
      if (this.query.subject_id && this.query.directory_id) {
        // 取出一级
        const top = this.treeList.find(
          (val) => val.id == this.query.subject_id
        );
        // 取出二级
        const child = top.children.find(
          (val) => val.id == this.query.directory_id
        );
        return child.children;
      } else {
        return [];
      }
    },
  },
  methods: {
    async get_list() {
      try {
        const res = await getQuestionList(this.query);
        this.list = res.data.list;
        this.total = parseInt(res.data.total);
        this.$nextTick(() => {
          this.multipleSelection = this.selectList;
          let newList = [];
          this.multipleSelection.forEach((item) => {
            newList.push(...this.list.filter((key) => key.id === item.id));
          });
          newList.forEach((row) => {
            this.$refs.tableList.toggleRowSelection(row);
          });
        });
      } catch (error) {
        console.log(error);
      }
    },

    async getTreeList() {
      this.query.quest_type = this.quest_type;
      try {
        const res = await getTreeList();
        console.log(res);
        this.treeList = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    searchsubmit() {
      console.log(this.query);
      this.page = 1;
      this.get_list();
    },
    searchcancel() {
      this.query = {
        ...defaultItem,
        show_state: this.checkQuestionMode ? 1 : "",
        check_state: this.checkQuestionMode ? 2 : "",
        quest_type: "",
        page: "1",
        limit: "10",
      };
      this.time = [];
      this.get_list();
    },
    // 批量上下架
    async changeAllShow(type) {
      try {
        await this.$confirm(
          `确定批量${type == 1 ? "上架" : "下架"}这${
            this.multipleSelection.length
          }条数据吗？`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
      } catch (e) {
        return this.$message.info("已取消");
      }
      if (type == 1) {
        // 上架,必须要审核通过的才可以
        const id = this.multipleSelection
          .filter((val) => val.check_state === 2)
          .map((val) => val.id);
        if (id.length === 0)
          return this.$message.warning("所选试题都未审核通过");
        await editQuestionShow({ id, show_state: type });
        const nocheck = this.multipleSelection.length - id.length;
        this.$message.success(`上架成功${id.length}条数据`);
        nocheck &&
          this.$notify({
            title: "提示",
            message: `${nocheck}条数据还未审核通过，不能上架`,
            type: "warning",
          });
      } else if (type == 2) {
        // 下架，必须处于上架状态的才可下架
        const id = this.multipleSelection
          .filter((val) => val.show_state === 1)
          .map((val) => val.id);
        if (id.length === 0)
          return this.$message.warning("所选试题都已下架，无需操作");
        await editQuestionShow({ id, show_state: type });
        const nocheck = this.multipleSelection.length - id.length;
        this.$message.success(`下架成功${id.length}条数据`);
        nocheck &&
          this.$notify({
            title: "提示",
            message: `${nocheck}条数据已下架，无需操作`,
            type: "warning",
          });
      }
      this.multipleSelection = [];
      this.get_list();
    }, // 单个上下架
    async showHandler(val, show_state) {
      await editQuestionShow({ id: [val.id], show_state });
      this.$message.success(`${show_state == 1 ? "上架" : "下架"}成功`);
      this.get_list();
    },
    // 修改按钮
    editHandler(val) {
      if (val.show_state != 2) return this.$message("下架才可以修改");
      // 子父通信,传递修改id出去
      this.$emit("edit", val.id);
    },
    // 审核按钮
    checkHandler(val) {
      this.checkShow = true;
      this.checkFormData.id = val.id;
    },
    // 删除按钮事件
    async delHandler(val) {
      // 下架 即可删除
      if (val.show_state == 2) {
        // 删除操作
        try {
          await this.$confirm("确定删除吗,是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          });
        } catch (e) {
          return this.$message.info("已取消");
        }
        console.log(888);
        console.log(val);
        const res = await deleteQuestion([val.id]);
        console.log(res.msg);
        if (!res.success === "false") {
          this.$message.success("删除成功");
        } else {
          this.$message.error(res.msg);
        }
        // 页码退1
        if (this.page * 1 !== 1 && this.list.length === 1) {
          this.page--;
        }
        this.get_list();
      } else {
        // 提示
        this.$message.warning("下架情况下才可以删除");
      }
    },
    pagination_change() {
      console.log(this.query);
      this.get_list();
    },
    // 审核提交
    async checkSubmit() {
      await editQuestionCheck({ checklist: [this.checkFormData] });
      this.$message.success("提交成功");
      this.get_list();
      this.checkShow = false;
    },
    // 审核取消
    checkCancel() {
      this.checkFormData = {
        id: "",
        check_state: 2,
        check_remarks: "",
      };
      this.checkShow = false;
    },
    // toggleSelection(rows) {
    //   console.log(rows);
    //   if (rows) {
    //     rows.forEach((row) => {
    //       console.log(row);
    //       this.$refs.tableList.toggleRowSelection(row, true);
    //     });
    //   } else {
    //     this.$refs.tableList.clearSelection();
    //   }
    // },
  },
  created() {
    this.get_list();

    this.getTreeList();
  },
  mounted() {},
  beforeUpdate() {
    this.multipleSelection = this.selectList;
    console.log(999);
    console.log(this.multipleSelection);
    console.log(this.list);

    // newList = this.list;
  },
};
</script>

<style lang="scss" scoped>
.question-filter {
  background-color: #fff;
  padding: 0 16px;
}
.el-date-editor.el-input__inner {
  width: 260px;
}
.question-list .el-form-item {
  margin-bottom: 10px;
}
</style>
